from typing import Union, List, Optional
from fastapi import FastAPI, Form
from pydantic import BaseModel, Field, ValidationError, validator, validators
import uvicorn
from datetime import date
import sys
import os


class Addr(BaseModel):
    province: str
    city: str

class User(BaseModel):
    name: str
    age: int = Field(default=0, gt=0, lt=100)
    birth: Union[date, None] = None
    friends: List[int] = []
    description: Optional[str] = None
    addr: Addr

    @validator("name")
    def name_must_alpha(cls, value):
        assert value.isalpha(), "name must be alpha"
        return value

class Data(BaseModel):
    data: List[User]


app = FastAPI()

@app.get("/user/1")
def get_user():
    return {"user_id": 123456}


@app.get("/user01/{user_id}")
def get_user01(user_id):
    return {"user_id": user_id}

@app.get("/user02/{user_id}")
def get_user02(user_id: int):
    return {"user_id": user_id}

@app.get("/jobs/{kd}")
async def search_jobs(kd: str, city: Union[str, None] = None, xl: Union[str, None] = None):
    if city or xl:
        return {"kd": kd, "city": city, "xl": xl}
    return {"kd": kd}

@app.post("/get_data01")
async def get_data01(user: User):
    print(user, type(user))
    print(user.name, user.birth)
    print(user.dict())
    return user

@app.post("/get_data02")
async def get_data02(data: Data):
    print(data, type(data))
    print(data.dict())
    return data

@app.post("/register")
def register(username: str = Form(..., max_length=16, min_length=8, regex='[a-zA-Z]'), password: str = Form(..., max_length=16, min_length=8, regex='[0-9]')):
    print(f"username: {username}, password: {password}")
    return {"username": username}

if __name__ == '__main__':
    print(sys.argv)

    # 获取当前文件的完整路径
    file_path = __file__
    # 获取文件名
    file_name = os.path.basename(file_path)
    print(file_name)

    start_args = file_name.split(".py")[0] + ":app"

    uvicorn.run(start_args, host="127.0.0.1", port=8000, reload=True)